package com.liuwish.learn.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description
 * <p>Condition的学习及使用
 * </p>
 * DATE 2018/5/14.
 *
 * @author liuweishi.
 */
public class ConditionUse {
    final Lock lock=new ReentrantLock();
    final Condition condition=lock.newCondition();

//    public static void main(String[] args) throws InterruptedException {
//        ConditionUse conditionUse=new ConditionUse();
//        Consumer consumer=conditionUse.new Consumer();
//        Producer producer=conditionUse.new Producer();
//        consumer.start();
//        producer.start();
//
//    }
    class Consumer extends Thread{
        @Override
        public void run() {
            consume();
        }
        private void consume(){
            try {
                lock.lock();
                System.out.println("我在等待信息号"+this.currentThread().getName());
                //进入等待状态，释放锁
                condition.await();
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                System.out.println("我拿到一个信号"+this.currentThread().getName());
                lock.unlock();
            }
        }
    }
    class Producer extends Thread{
        @Override
        public void run() {
            produce();
        }
        private void produce(){
            try {
                lock.lock();
                System.out.println("我拿到锁"+this.currentThread().getName());
                //通知其他线程进入获取锁状态，本线程释放锁后，其他线程才可获得锁
                condition.signalAll();
                System.out.println("我发出一个信号"+this.currentThread().getName());
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    public static void main(String[] args) {
        int [] arr={1,1,1,2,4,4,5};
        removeDuplicatesN(arr);
    }
    public static int removeDuplicatesN(int[] nums) {
        if (nums.length <1) return nums.length;
        int index = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[index]) {
                nums[++index] = nums[i];
            }
        }

        for (int i = 0; i < index+1; i++) {
            System.out.println(nums[i]);
        }
        return index;
    }
}
